



# Register all parsers and other extensions


Token_Parsers = {}
Language_Parsers = {}
Language_Recognition = {}

# Reg a token parser
def RegParser(id="", condition=None):
    def _ParseFun_(fun):
        global Token_Parsers
        if id not in Token_Parsers:
            Token_Parsers[id] = {}
        Token_Parsers[id]['condition'] = condition
        Token_Parsers[id]['parser'] = fun
        
    return _ParseFun_

# Reg a post token parser
def RegPostParser(id="", post_condition=None):
    def _ParsePostFun_(fun):
        global Token_Parsers
        if id not in Token_Parsers:
            Token_Parsers[id] = {}
        Token_Parsers[id]['post_condition'] = post_condition
        Token_Parsers[id]['post_parser'] = fun
    
    return _ParsePostFun_

# Reg keyword as post token parser
def RegKeyword(val):
    def MarkTokenAsKeyword(tok):
        tok['type'] = 'tok_keyword'
        return (True, tok )
    id = "Keyword_" + val
    global Token_Parsers
    if id not in Token_Parsers:
        Token_Parsers[id] = {}
    Token_Parsers[id]['post_condition'] = [val]
    Token_Parsers[id]['post_parser'] = MarkTokenAsKeyword


# Reg a symbol
# RegSymbol("+", "operator_add")
def RegSymbol(symbol, stype):
    class SymbolMatcher:
        def __init__(self, symbol, stype):
            self.__symbol__ = symbol
            self.__symbol_type__ = stype
        def is_symbol(self, pos, content):
            return self.__symbol__ == content[pos: pos+len(self.__symbol__)]
        def parse_symbol(self, content, offset):
            return (True, self.__symbol__, offset+len(self.__symbol__), "tok_" + self.__symbol_type__)

    ptmp = SymbolMatcher(symbol, stype)

    id = "Symbol_" + stype
    global Token_Parsers
    if id not in Token_Parsers:
        Token_Parsers[id] = {}
    Token_Parsers[id]['condition'] = ptmp.is_symbol
    Token_Parsers[id]['parser'] = ptmp.parse_symbol
 

def rbracket_noname(content, offset):
    pre = offset
    return (True, ")", offset+1, "tok_rbracket")

# Reg language bind parsers
def RegLanguage(language = "", extension=[]):
    def _ParsersByLanguage_(fun):
        global Language_Parsers
        global Language_Recognition
    
        Language_Parsers[language] = fun
        for ext in extension:
            Language_Recognition[ext] = language
    
    return _ParsersByLanguage_
